package com.eb.buybuybuy.context;

import com.eb.buybuybuy.util.MysqlUtil;

import java.sql.Connection;
import java.sql.SQLException;

public class TransactionContext {
    private static ThreadLocal<Connection> transactionThreadLocal = new ThreadLocal<>();

    public static void start() throws SQLException {
        // 如果已经开启，使用之前的连接
        if (!isOpening()) {
            Connection connection = MysqlUtil.getConnection();
            connection.setAutoCommit(false);
            transactionThreadLocal.set(connection);
        }
    }

    public static void commit() throws SQLException {
        Connection connection = getConnection();
        connection.commit();
        closeConnection(connection);
    }

    public static void rollback() throws SQLException {
        Connection connection = getConnection();
        connection.rollback();
        closeConnection(connection);
    }

    public static Connection getConnection() {
        return transactionThreadLocal.get();
    }

    private static void closeConnection(Connection connection) throws SQLException {
        connection.setAutoCommit(true);
        connection.close();
        transactionThreadLocal.remove();
    }

    public static Boolean isOpening() {
        return transactionThreadLocal.get() != null;
    }
}
